<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--用户数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
              label-width="68px">
              <el-form-item label="用户姓名" prop="userName">
                <el-input v-model="queryParams.userName" placeholder="请输入用户姓名" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="手机号码" prop="phoneNumber">
                <el-input v-model="queryParams.phoneNumber" placeholder="请输入手机号码" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item v-hasRole="['admin']" label="用户类型" prop="userType">
                <el-select v-model="queryParams.userType" placeholder="用户类型" clearable style="width: 240px">
                  <el-option v-for="dict in dict.type.user_type" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item v-hasRole="['admin']" label="是否会员" prop="isVip">
                <el-select v-model="queryParams.isVip" placeholder="是否会员" clearable style="width: 240px">
                  <el-option v-for="dict in dict.type.app_is_vip" :key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item v-hasRole="['admin']" label="邀请人" prop="inviterName">
                <el-input v-model="queryParams.inviterName" placeholder="请输入邀请人姓名" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item v-hasRole="['admin']" label-width="120px" label="邀请人手机号码" prop="inviterPhoneNumber">
                <el-input v-model="queryParams.inviterPhoneNumber" placeholder="请输入手机号码" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="注册时间">
                <el-date-picker v-model="dateRange" value-format="yyyy-MM-dd" type="daterange" range-separator="至"
                  start-placeholder="开始日期" end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增
                </el-button>
              </el-col>

              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center" />
              <!-- <el-table-column label="用户编号" align="center" key="userId" prop="userId" /> -->
              <el-table-column label="用户姓名" min-width="120px" align="center" prop="userName"
                :show-overflow-tooltip="true" />
              <el-table-column label="手机号码" min-width="220px" align="center" prop="phoneNumber" />
              <el-table-column label="用户类型" min-width="120px" align="center" prop="userType"
                :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.user_type" :value="scope.row.userType" />
                </template>
              </el-table-column>
              <el-table-column label="会员状态" min-width="120px" align="center" prop="isVip" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.app_is_vip" :value="scope.row.isVip" />
                </template>
              </el-table-column>
              <el-table-column label="状态" min-width="120px" align="center" prop="status" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.app_user_status" :value="scope.row.status" />
                </template>
              </el-table-column>
              <el-table-column label="会员到期时间" min-width="150px" align="center" prop="vipEndDate" />
              <el-table-column label="邀请人" align="center" min-width="220px">
                <template slot-scope="scope">
                  {{ scope.row.inviterName && scope.row.inviterPhoneNumber ? scope.row.inviterName + '-' +
                    scope.row.inviterPhoneNumber : scope.row.inviterPhoneNumber || '' }}
                </template>
              </el-table-column>
              <el-table-column label="创建时间" min-width="150px" align="center" prop="createTime">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="最近登录时间" min-width="150px" align="center" prop="loginDate">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.loginDate) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width"
                fixed="right">
                <template slot-scope="scope" v-if="scope.row.userId !== 1">
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
                  </el-button>
                  <el-button v-hasRole="['admin']" size="mini" type="text" icon="el-icon-delete"
                    @click="handleDelete(scope.row)">删除
                  </el-button>
                  <el-button v-if="scope.row.userType == 1" size="mini" type="text" icon="el-icon-s-promotion"
                    @click="handleOpenPromotion(scope.row)">推广数据
                  </el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row v-hasRole="['admin']">
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20" show-password />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="userType">
              <el-select v-model="form.userType" placeholder="请选择用户类型" clearable>
                <el-option v-for="dict in dict.type.user_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="会员状态" prop="isVip">
              <el-select v-model="form.isVip" placeholder="请选择会员状态" clearable>
                <el-option v-for="dict in dict.type.app_is_vip" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.isVip == 1">
            <el-form-item label="会员时长(月)" prop="vipOpeningCycle">
              <el-input v-model="form.vipOpeningCycle" placeholder="请输入会员时长" type="number" />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.userType == 1">
            <el-form-item label="推广比例" prop="promotionType">
              <el-select v-model="form.promotionType" placeholder="请选择推广比例" clearable>
                <el-option v-for="dict in promotionOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-hasRole="['agent']">
          <el-col :span="12">
            <el-form-item label="用户名称" prop="userName">
              <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input v-model="form.phoneNumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="推广比例" prop="promotionType">
              <el-select v-model="form.promotionType" placeholder="请选择推广比例" clearable>
                <el-option v-for="dict in promotionOptions" :key="dict.id" :label="dict.name" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 推广 -->
    <el-dialog title="推广数据" :visible.sync="promotionShow" width="700px" append-to-body>

      <el-descriptions class="margin-top" :column="1" border>
        <el-descriptions-item label="分成比例"> {{ promotionData.settlementProportion }}</el-descriptions-item>
        <el-descriptions-item label="总注册数">
          {{ promotionData.registerUserNums }}
        </el-descriptions-item>
        <el-descriptions-item label="总会员数">
          {{ promotionData.vipUserNums }}
        </el-descriptions-item>
        <el-descriptions-item label="本月收益">
          {{ promotionData.currentRevenue }}
        </el-descriptions-item>
        <el-descriptions-item label="本月注册人数">
          {{ promotionData.currentRegisterUserNum }}
        </el-descriptions-item>
        <el-descriptions-item label="本月会员数">
          {{ promotionData.currentVipUserNum }}
        </el-descriptions-item>
        <el-descriptions-item label="上月收益(代发放)">
          {{ promotionData.beforeRevenue }}
        </el-descriptions-item>
        <el-descriptions-item label="累计收益">
          {{ promotionData.accumulatedIncome }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <!-- <el-button type="primary" @click="submitForm">确 定</el-button> -->
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listAppUser,
  getAppUser,
  getUser,
  delAppUser,
  addAppUser,
  updateAppUser,
  getPromotionContentr
} from "@/api/system/user";
import { promotionList } from "@/api/promotion/index";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { checkPermi, checkRole } from "@/utils/permission"; // 权限判断函数

export default {
  name: "User",
  dicts: ["user_type", "app_is_vip", "sys_normal_disable", "sys_user_sex", "app_user_status"],
  components: { Treeselect, Splitpanes, Pane },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: "",
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/user/importData",
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: 'createTime',
        isAsc: 'descending',
        userName: undefined,
        phoneNumber: undefined,
        userType: undefined,
        isVip: undefined,
        inviterName: undefined,
        inviterPhoneNumber: undefined,
      },
      // 表单校验
      rules: {
        // userName: [
        //   { required: true, message: "用户名称不能为空", trigger: "blur" },
        //   {
        //     min: 2,
        //     max: 20,
        //     message: "用户名称长度必须介于 2 和 20 之间",
        //     trigger: "blur",
        //   },
        // ],
        phoneNumber: [
          { required: true, message: "用户手机号不能为空", trigger: "blur" },
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        userType: [
          { required: true, message: "用户类型必选", trigger: "blur" },
        ],
        // promotionType: [
        //   { required: true, message: "推广比例必选", trigger: "blur" },
        // ],
        isVip: [
          { required: true, message: "用户会员状态必选", trigger: "blur" },
        ],
        // vipOpeningCycle: [
        //   { required: true, message: "用户会员时长必填", trigger: "blur" },
        // ],
      },

      // 推广数据
      promotionData: {},
      promotionShow: false,
      promotionOptions: [],

    };
  },
  watch: {
    'form.userType': {
      handler(newVal) {
        if (newVal == 1) {
          console.log(222)
          this.rules.promotionType = [{ required: true, message: "推广比例必选", trigger: "blur" },];
          this.rules.vipOpeningCycle = [{ required: true, message: "用户会员时长必填", trigger: "blur" },];
        } else {
          console.log(333)
          this.rules.promotionType = [{ required: false, message: "推广比例必选", trigger: "blur" },];
          this.rules.vipOpeningCycle = [{ required: false, message: "用户会员时长必填", trigger: "blur" },];
        }
      },
      immediate: true,
    }
  },
  created() {
    this.getList();
    this.getPromotionList()
  },
  methods: {
    /** 查询用户列表 */
    getList() {
      this.loading = true;
      listAppUser(this.addDateRange(this.queryParams, this.dateRange)).then(
        (response) => {
          this.userList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },

    // 获取推广比例
    getPromotionList() {
      promotionList().then(
        (response) => {
          this.promotionOptions = response.rows;
        }
      );
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.promotionShow = false
      this.reset();
    },
    // 表单重置
    reset() {
      if (checkRole(['agent'])) {
        this.rules.promotionType = [{ required: true, message: "推广比例必选", trigger: "blur" }];
      }
      this.form = {
        userId: undefined,
        userName: undefined,
        phoneNumber: undefined,
        isVip: '0',
        vipOpeningCycle: undefined,
        userType: checkRole(['admin']) ? undefined : '1',
        status: "0",
        promotionType: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.queryParams.deptId = undefined;
      this.$refs.tree.setCurrentKey(null);
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.userId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // getUser().then((response) => {
      this.open = true;
      this.title = "添加用户";
      // });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const userId = row.userId;

      getAppUser(userId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改用户";
      });
    },

    /** 推广数据操作 */
    handlePromotion: function (row) {
      const userId = row.userId;
      this.$router.push("/system/user-auth/role/" + userId);
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.userId != undefined) {
            if (this.form.userType == 0) {
              this.form.promotionType = null
            }
            this.form.vipOpeningCycle = this.form.vipOpeningCycle ? parseInt(this.form.vipOpeningCycle) : undefined
            updateAppUser(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.vipOpeningCycle = this.form.vipOpeningCycle ? parseInt(this.form.vipOpeningCycle) : undefined
            addAppUser(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const userIds = row.userId || this.ids;
      this.$modal
        .confirm('是否确认删除用户编号为"' + userIds + '"的数据项？')
        .then(function () {
          return delAppUser(userIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/user/export",
        {
          ...this.queryParams,
        },
        `user_${new Date().getTime()}.xlsx`
      );
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download(
        "system/user/importTemplate",
        {},
        `user_template_${new Date().getTime()}.xlsx`
      );
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(
        "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" +
        response.msg +
        "</div>",
        "导入结果",
        { dangerouslyUseHTMLString: true }
      );
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },


    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.handleQuery();
    },


    // 打开推广数据弹窗
    handleOpenPromotion(row) {
      getPromotionContentr({ userId: row.userId }).then(res => {
        this.promotionData = res.data.data
      })

      this.promotionShow = true;
      this.promotionDialog = true;
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-descriptions-item__label.is-bordered-label {
  width: 200px;
}
</style>
